<template>
  <div>
    <!-- Top -->
    <van-nav-bar title="会员登录" left-text="返回" left-arrow />
    <!-- 标题 -->
    <div class="txt">
      <h1>手机号登录</h1>
      <p>未注册的手机号登录后将自动注册</p>
    </div>
    <!-- form表单 -->
    <van-form >
      <!-- 手机号 -->
      <van-field
        v-model="mobile"
        name="pattern"
        placeholder="请输入手机号码"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '手机号必须11个字符',
          },
        ]"
      />
      <!-- 图片验证码 -->
      <van-field
        v-model="captchaCode"
        center
        clearable
        placeholder="请输入图片验证码"
        :rules="[{ required: true, message: '请填写图片验证码' }]"
      >
        <template #right-icon>
          <div
            style="display: flex; align-items: center; justify-content: center"
          >
            <van-image
              :src="captchaUrl"
              width="96px"
              height="25px"
              @click="urlFn"
            />
          </div>
        </template>
      </van-field>
      <!-- 短信验证码 -->
      <van-field
        v-model="smsCode"
        center
        clearable
        placeholder="测试环境验证码为246810"
        :rules="[{ required: true, message: '请输入正确内容' }]"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendFn"
            >发送验证码</van-button
          >
        </template>
      </van-field>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" @click="loginFn"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { getImg, getCode, LoginIn } from '../api/user'
export default {
  name: 'loginCom',
  data () {
    return {
      mobile: '', // 手机号
      captchaCode: '', // 图片验证码
      captchaKey: '', // 图形验证码key
      smsCode: '', // 手机验证码
      // 图片赋值到这里
      captchaUrl: ''
    }
  },
  async created () {
    // 页面刷新渲染图片
    const res = await getImg()
    this.captchaUrl = res.data.base64
    this.captchaKey = res.data.key
  },
  methods: {
    // 点击切换图片
    async urlFn () {
      const res = await getImg()
      console.log(res)
      this.captchaUrl = res.data.base64
      this.captchaKey = res.data.key
      // console.log(this.captchaUrl, this.captchaKey)
    },
    // onSubmit (values) {
    //   console.log('submit', values)
    // },
    async sendFn () {
      const res = await getCode({
        captchaUrl: this.captchaUrl,
        captchaKey: this.captchaKey,
        mobile: this.mobile
      })
      console.log(res, '手机验证码')
    },
    async loginFn () {
      const res = await LoginIn({
        mobile: this.mobile,
        smsCode: this.smsCode
      })
      console.log(res, '登录返回的数据')
      this.$router.push('/home')
    }
  }
}
</script>

<style scoped>
.form {
  margin: 20px;
}
.txt {
  margin: 20px;
}
p {
  color: #9e8d98;
}
btn {
  background-color: #f1ab30;
}
</style>
